import datetime
import json
import os.path
import random
import time

import requests
from django.db import connection
from django.shortcuts import render
from .models import *
import pprint as pp
from django.http import HttpResponse, JsonResponse
from django.core.paginator import Paginator  #实现分页的类
import numpy as np
import matplotlib.pyplot as plt

collect_date = '2023-11-01'
collect_date = datetime.datetime.strptime(collect_date, "%Y-%m-%d")

market_arr = {
        1: '正和农贸市场',
        2: '北站市场',
        3: '胜利新菜市',
        4: '白沙农贸综合市场',
        5: '北雀农贸综合市场',
        6: '胜利商贸城农贸市场',
        7: '华保农贸市场',
        8: '永丰农贸市场',
        9: '盛世农贸市场',
        10: '小鹅山过度市场'
}

cid1_arr = {
    1186: 1,
    1187: 2,
    1189: 3,
    1190: 4,
    1188: 5,
    1203: 6,
    1204: 7,
}

cid2_arr = {
    1199: 1,
    1200: 2,
    1201: 3,
    1202: 4,
    1205: 5,
    1206: 6,
    1207: 7,
    1208: 8,
    1209: 9,
    1210: 10,
    1217: 11,
    1218: 12,
    1211: 13,
    1212: 14,
    1213: 15,
    1214: 16,
}

# 一级分类信息
category1_arr = {c1.id: c1.category_name for c1 in Category1.objects.all()}
category1_arr[0] = ''

# 二 级分类信息
category2_arr = {c2.id: c2.category_name for c2 in Category2.objects.all()}
category2_arr[0] = ''


# 基础信息
def index(request):
    json_data = {
        'message': 'OK'
    }
    content = {
        'list': [1, 2, 3, 4]
    }

    return render(request, 'baseinfo/index.html', content)


def crawler(request):
    json_data = {
        'message': 'OK'
    }

    post_url = 'http://xinfadi.com.cn/getPriceData.html'
    pubDateEndTime = pubDateStartTime = collect_date

    i = 1
    while i <= 10:
        print('第 ' + str(i) + ' 页')
        post_json_data = {
            'current': i,
            'limit': 20,
            # 'pubDateStartTime': pubDateStartTime,
            # 'pubDateEndTime': pubDateEndTime,
        }

        response = requests.post(post_url, data=post_json_data)
        content = response.json()
        list = content['list']

        for market in market_arr:
            for li in list:
                if not li['prodCatid']:
                    cid1 = 0
                else:
                    cid1 = cid1_arr[li['prodCatid']]

                if not li['prodPcatid']:
                    cid2 = 0
                else:
                    if li['prodPcatid'] not in cid2_arr:
                        cid2 = 0
                    else:
                        cid2 = cid2_arr[li['prodPcatid']]


                market_name = market_arr[market]
                product_name = li['prodName']
                min_price = li['lowPrice'].replace('..', '.')
                avg_price = li['avgPrice'].replace('..', '.')
                max_price = li['highPrice'].replace('..', '.')
                standards = li['specInfo']
                place = li['place'] if li['place'] else ''
                unit = li['unitInfo']
                pub_date = li['pubDate'].split(' ')[0]

                detail = Detail(
                                cid1=cid1, cid2=cid2, market_name=market_name, product_name=product_name, min_price=min_price,
                                avg_price=avg_price, max_price=max_price, standards=standards, place=place, unit=unit,
                                pub_date=pub_date
                )
                detail.save()
        i += 1
    time.sleep(0.5)

    return JsonResponse(json_data)


# 根据当前页获取数据
def get_detail_data_by_page(request, current_page, page_size):
    json_data = {
        'message': '没有获取到数据',
        'list': [],
        'total': 0
    }

    if current_page.isdigit() and page_size.isdigit():
        current_page = 1 if int(current_page) <= 0 else int(current_page)
        display = 100 if int(page_size) <= 0 else int(page_size)

        start = (current_page - 1) * display
        sql = "SELECT * FROM `newmarket_detail` ORDER BY pub_date DESC LIMIT " + str(start) + ", " + str(display) + ";"
        data = Detail.objects.raw(sql)

        # 拼返回数据
        list = []
        if data:
            for d in data:
                detail = {
                    'id': d.id,
                    'category1': category1_arr[d.cid1],
                    'category2': category2_arr[d.cid2],
                    'market_name': d.market_name,
                    'product_name': d.product_name,
                    'min_price': d.min_price,
                    'avg_price': d.avg_price,
                    'max_price': d.max_price,
                    'standards': d.standards,
                    'place': d.place,
                    'unit': d.unit,
                    'pub_date': d.pub_date
                }
                list.append(detail)

            json_data['message'] = 'OK'
            json_data['list'] = list
            json_data['total'] = Detail.objects.all().count()

    return JsonResponse(json_data)


# 获取行情分析
def get_info(request):
    '''
    获取上月同日数据生成柱状图
    '''
    json_data = {
        'message': '没有获取到数据',
        'list': []
    }

    # 今天
    today = datetime.date.today()
    first_day = today.replace(day=1)

    # 要生成图片的信息
    # 一二级分类
    cate1_arr = [3, 3, 3]
    cate2_arr = [5, 5, 6]
    product_arr = ['白条猪', '白条猪', '牛柳']
    standards_arr = ['瘦', '肥', '里脊']
    unit_arr = ['斤', '斤', '斤']
    pic_url = []

    for market in market_arr:
        # x轴数据
        x_data = [
            collect_date.replace(month=collect_date.month - 7),
            collect_date.replace(month=collect_date.month - 6),
            collect_date.replace(month=collect_date.month - 5),
            collect_date.replace(month=collect_date.month - 4),
            collect_date.replace(month=collect_date.month - 3),
            collect_date.replace(month=collect_date.month - 2),
            collect_date.replace(month=collect_date.month - 1),
            collect_date,
        ]



        key = 0
        key_end = len(cate1_arr)
        while key < key_end:
            cid1 = cate1_arr[key]
            cid2 = cate2_arr[key]
            product_name = product_arr[key]
            standards = standards_arr[key]
            unit = unit_arr[key]

            # y轴数据
            y_data = []
            for pub_date in x_data:
                tmp_data = Detail.objects.filter(pub_date=pub_date) \
                    .filter(cid1=cid1) \
                    .filter(cid2=cid2) \
                    .filter(product_name=product_name) \
                    .filter(standards=standards) \
                    .filter(market_name=market_arr[market])
                y_data.append(tmp_data[0].avg_price)


            # 正确显示中文和负号
            plt.rcParams["font.sans-serif"] = ["SimHei"]
            plt.rcParams["axes.unicode_minus"] = False

            for i in range(len(x_data)):
                plt.bar(str(x_data[i]).split(' ')[0].split('-')[1], y_data[i], width=0.5)

            # 设置图片名称
            title = '{}-{}-{} 价格走势'.format(market_arr[market], product_name, standards)
            plt.title(title)

            # 设置x轴标签名
            plt.xlabel('月份')

            # 设置y轴标签名
            plt.ylabel('元 / ' + unit)

            # 生成图片
            current_month = datetime.datetime.now().strftime("%Y")
            pic_name = './static/pic/{}-c1-{}-c2-{}-m-{}-k-{}.png'.format(current_month, cid1,
                                                                       cid2, market, key)

            if os.path.exists(pic_name):
                modify_time = int(os.path.getmtime(pic_name))
                current_time = int(time.time())
                sub_time = (current_time - modify_time) / 3600

                if sub_time >= 3:
                    plt.savefig(fname=pic_name, dpi=100)
                    time.sleep(0.5)
                    plt.clf()
            else:
                plt.savefig(fname=pic_name, dpi=100)
                time.sleep(0.5)
                plt.clf()

            pic_info = {
                'url': pic_name,
                'title': title,
            }
            pic_url.append(pic_info)
            key += 1

    json_data['message'] = 'OK'
    json_data['list'] = pic_url
    return JsonResponse(json_data)


# 今日行情
def get_today_by_market_id(request, market_id):
    json_data = {
        'message': '没有获取到数据',
        'list': []
    }

    if market_id.isdigit():
        market_id = int(market_id)
        if market_id in market_arr:
            tmp_list = Detail.objects.filter(market_name=market_arr[market_id]).filter(pub_date=collect_date)
            if tmp_list:
                ret_list = []
                for detail in tmp_list:
                    detail = {
                        'id': detail.id,
                        'category1': category1_arr[detail.cid1],
                        'category2': category2_arr[detail.cid2],
                        'market_name': detail.market_name,
                        'product_name': detail.product_name,
                        'min_price': detail.min_price,
                        'avg_price': detail.avg_price,
                        'max_price': detail.max_price,
                        'standards': detail.standards,
                        'place': detail.place,
                        'unit': detail.unit,
                        'pub_date': detail.pub_date

                    }
                    ret_list.append(detail)

                json_data['message'] = 'OK'
                json_data['list'] = ret_list

    return JsonResponse(json_data)


# 获取市场信息
def get_market_info(request):
    json_data = {
        'message': 'OK',
        'list': []
    }

    for key in market_arr:
        tmp = {'marketname': market_arr[key], 'key': key}
        json_data['list'].append(tmp)

    return JsonResponse(json_data)


# 提交查询
def search(request):
    json_data = {
        'message': '没有查询到数据',
        'list': [],
        'total': 0
    }

    if request.method == 'POST':
        concurrent_date = datetime.datetime.now().strftime("%Y-%m-%d")

        # 接收查询数据
        body = json.loads(request.body)

        current_page = body.get('current_page')
        page = 1 if int(current_page) < 1 else int(current_page)

        display = body.get('page_size')
        display = 100 if int(display) <= 0 else int(display)

        start_date = body.get('start_date')
        end_date = body.get('end_date')
        market_name = body.get('market_name')
        product_name = body.get('product_name')

        if (not start_date) and (not end_date):
            return JsonResponse(json_data)

        if start_date and (not end_date):
            end_date = start_date

        if end_date and (not start_date):
            end_date = start_date

        if not market_name:
            market_name = market_arr[1]

        start = (current_page - 1) * display

        # 判断是否输入了菜品名称
        if not product_name:
            data = Detail.objects.order_by('-pub_date')\
                .filter(market_name=market_name)\
                .filter(pub_date__gte=start_date)\
                .filter(pub_date__lte=end_date)

            if data:
                for d in data:
                    detail = {
                        'id': d.id,
                        'category1': category1_arr[d.cid1],
                        'category2': category2_arr[d.cid2],
                        'market_name': d.market_name,
                        'product_name': d.product_name,
                        'min_price': d.min_price,
                        'avg_price': d.avg_price,
                        'max_price': d.max_price,
                        'standards': d.standards,
                        'place': d.place,
                        'unit': d.unit,
                        'pub_date': d.pub_date
                    }
                    json_data['list'].append(detail)

                json_data['total'] = Detail.objects.filter(market_name=market_name)\
                    .filter(pub_date__gte=start_date)\
                    .filter(pub_date__lte=end_date)\
                    .count()
                json_data['message'] = 'OK'
        else:
            sql1 = '''
                SELECT *
                FROM newmarket_detail
                WHERE product_name LIKE %s
                AND market_name = %s
                AND pub_date >= %s
                AND pub_date <= %s
                ORDER BY pub_date DESC
                LIMIT %s, %s
            '''

            params = ['%' + product_name + '%', market_name, start_date, end_date, start, display]
            with connection.cursor() as cursor:
                cursor.execute(sql1, params)
                data = cursor.fetchall()

            if data:
                for d in data:
                    detail = {
                        'id': d[0],
                        'category1': category1_arr[d[1]],
                        'category2': category2_arr[d[2]],
                        'market_name': d[3],
                        'product_name': d[4],
                        'min_price': d[5],
                        'avg_price': d[6],
                        'max_price': d[7],
                        'standards': d[8],
                        'place': d[9],
                        'unit': d[10],
                        'pub_date': d[11]

                    }
                    json_data['list'].append(detail)

                sql2 = '''
                    SELECT COUNT(*) total
                    FROM newmarket_detail
                    WHERE product_name LIKE %s
                    AND market_name = %s
                    AND pub_date >= %s
                    AND pub_date <= %s
                '''

                params = ['%' + product_name + '%', market_name, start_date, end_date]
                with connection.cursor() as cursor:
                    cursor.execute(sql2, params)
                    count_data = cursor.fetchone()

                json_data['total'] = count_data[0]
                json_data['message'] = 'OK'

    return JsonResponse(json_data)